<?php

namespace App\Services\Api\Login;

use App\Daos\Api\Login\UserDao;
use App\Services\Api\Other\OtherService;
use Illuminate\Support\Facades\Redis;

class UserService
{
    public static function slient ($code){
        $url = sprintf(config('wx.url'),$code);
        $res = json_decode(file_get_contents($url),true);
        $id = UserDao::slient($res['openid'],$res['session_key']);
        if (!$id){
            throw new \Exception('静默登录失败');
        }
        return OtherService::createToken($id);
    }

    public static function mandate ($data){
        $data['id'] = OtherService::parseToken($data['token']);
        unset($data['token']);
        $res = UserDao::mandate($data);
        if (!$res){
            throw new \Exception('授权失败');
        }
        return true;
    }

    public static function mobile ($data){
        if (!Redis::get($data['tel'])){
            throw new \Exception('请先获取验证码');
        }
        if ($data['code'] != Redis::get($data['tel'])){
            throw new \Exception('验证码错误');
        }
        $data['id'] = OtherService::parseToken($data['token']);
        unset($data['token']);
        UserDao::mobile($data);
    }

    public static function captcha ($tel){
        $now_date = date('Y-m-d');
        $now_time = time();
        if (!Redis::get($now_date.$tel) || Redis::get($now_date.$tel) >= 5){
            throw new \Exception('该手机号当前验证码发送次数已达上限');
        }
        if ($now_time - Redis::get($tel.'first') ?: 0 < 60){
            $num = 60 - ($now_time - Redis::get($tel.'first'));
            throw new \Exception('短信正在发送，请' . $num . '秒后再试');
        }
        Redis::setex($tel.'first',61,time());
        $code = Redis::get($tel);
        if (!$code){
            $code = rand(100000,999999);
            Redis::setex($tel,300,$code);
        }
        if (!Redis::get($now_date.$tel)){
            Redis::set($now_date.$tel);
        } else {
            Redis::incr($now_date.$tel);
        }
        $res = OtherService::sendCode($tel,$code);
        if (!$res || $res != 0){
            throw new \Exception('短信发送失败，请重试或联系客服');
        }
        return true;
    }
}
